package com.jz.community.moduleshoppingguide.nearshop.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.BaseCommLocateInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.loaction.LocationActivity;
import com.jz.community.basecomm.loaction.LocationManager;
import com.jz.community.basecomm.loaction.PoiManager;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.commview.view.MyStateView;
import com.jz.community.commview.view.RelativePopupWindow;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.nearshop.bean.CategoriesBean;
import com.jz.community.moduleshoppingguide.nearshop.bean.ShopDownStairsBean;
import com.jz.community.moduleshoppingguide.nearshop.presenter.NearShopPresenter;
import com.jz.community.moduleshoppingguide.nearshop.ui.NearShopView;
import com.jz.community.moduleshoppingguide.nearshop.ui.adapter.NearShopAdapter;
import com.jz.community.moduleshoppingguide.nearshop.ui.view.ShopCategorysPop;
import com.jz.community.moduleshoppingguide.search.ui.SearchActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

@Route(path = RouterIntentConstant.NEAR_SHOP)
public class NearShopActivity extends BaseMvpActivity<NearShopView.View, NearShopPresenter> implements NearShopView.View, OnRefreshListener, ShopCategorysPop.PopTypeChoose, BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R2.id.near_shop_back)
    ImageView nearShopBack;
    @BindView(R2.id.near_shop_title)
    TextView nearShopTitle;
    @BindView(R2.id.near_shop_address)
    TextView nearShopAddress;//定位信息
    @BindView(R2.id.near_shop_address_ll)
    LinearLayout nearShopAddressLl;//定位点击
    @BindView(R2.id.near_shop_search)
    ImageView nearShopSearch;//搜索
    @BindView(R2.id.near_shop_toolbar)
    Toolbar nearShopToolbar;
    @BindView(R2.id.near_shop_top_content)
    TextView nearShopTopContent;//展示附近3公里内的楼下小店
    @BindView(R2.id.near_shop_top_btn)
    TextView nearShopTopBtn;//展示全部，点击
    @BindView(R2.id.near_shop_top_rl)
    RelativeLayout nearShopTopRl;
    @BindView(R2.id.near_shop_sel_all_tv)
    TextView nearShopSelAllTv;//全部分类
    @BindView(R2.id.near_shop_sel_all_iv)
    ImageView nearShopSelAllIv;//上下箭头
    @BindView(R2.id.near_shop_sel_all_ll)
    LinearLayout nearShopSelAllLl;
    @BindView(R2.id.near_shop_sel_near_tv)
    TextView nearShopSelNearTv;//离我最近
    @BindView(R2.id.near_shop_sel_near_ll)
    LinearLayout nearShopSelNearLl;
    @BindView(R2.id.near_shop_sel_express_tv)
    TextView nearShopSelExpressTv;//支持配送
    @BindView(R2.id.near_shop_sel_express_ll)
    LinearLayout nearShopSelExpressLl;
    @BindView(R2.id.near_shop_sel_ll)
    LinearLayout nearShopSelLl;
    @BindView(R2.id.near_shop_rv)
    RecyclerView nearShopRv;
    @BindView(R2.id.near_shop_refresh)
    SmartRefreshLayout nearShopRefresh;
    @BindView(R2.id.near_shop_parent)
    LinearLayout nearShopParent;
    MyStateView myStateView;
    private View noDataView;
    private View errorView;
    private View locationView;

    String limitDistance = "";
    String mainBusinessId = "";
    String mLon = "";
    String mLat = "";
    int page = 0;
    int size = 10;

    private static final int CODE_COMMUNITY = 0X00001;
    private ShopCategorysPop shopCategorysPop;
    private NearShopAdapter nearShopAdapter;
    private int fromFlag = 0;
    private int sort = 0;

    @Override
    protected int getContentView() {
        return R.layout.module_shoppingguide_activity_near_shop;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected NearShopPresenter createPresenter() {
        return new NearShopPresenter(this);
    }


    @Override
    protected void initView() {
        setImmersionBar(nearShopToolbar);
        nearShopTitle.setText("楼下小店");
        nearShopRv.setLayoutManager(new LinearLayoutManager(this));
        nearShopAdapter = new NearShopAdapter(R.layout.module_shoppingguide_item_near_shop_main, new ArrayList<>());
        nearShopRv.setAdapter(nearShopAdapter);
        nearShopRefresh.setEnableLoadMore(false);
        nearShopRefresh.setOnRefreshListener(this);
        nearShopAdapter.setOnLoadMoreListener(this, nearShopRv);
        fromFlag = getIntent().getIntExtra("fromFlag", 0);
        myStateView = new MyStateView();
        noDataView = myStateView.getNoDataView(this, (ViewGroup) nearShopRv.getParent(), "暂无店铺！", null);
        errorView = myStateView.getErrorView(this, (ViewGroup) nearShopRv.getParent(), v -> getData(1, sort));
        locationView = myStateView.getLocationView(this, (ViewGroup) nearShopRv.getParent(),
                v -> {
                    //手动定位
                    Intent toCommunity = new Intent(NearShopActivity.this, LocationActivity.class);
                    startActivityForResult(toCommunity, CODE_COMMUNITY);
                }, v -> {
                    //重新定位
                    beginLocation();
                });
        if (fromFlag == 0) {
            beginLocation();
        } else {
            double mLatitude = getIntent().getDoubleExtra("mLatitude", 0);
            double mLongitude = getIntent().getDoubleExtra("mLongitude", 0);
            lnToCommunity(mLatitude, mLongitude,"");
        }
        EventBus.getDefault().register(this);
    }

    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventBus(AppEvent message) {
        if (message.tag == EventConfig.ORDER_REFRESH) {
            finish();
        }
    }

    @Override
    protected void addListener() {
        nearShopBack.setOnClickListener(v -> finish());
        nearShopSelAllLl.setOnClickListener(v -> {
            chooseAll();
            if (shopCategorysPop == null) {
                mPresenter.showShopCategorys("platformId::101|shopType::2");
            } else {
                shopCategorysPop.showOnAnchor(nearShopSelLl, RelativePopupWindow.VerticalPosition.BELOW, RelativePopupWindow.HorizontalPosition.ALIGN_LEFT, 0, 0);
            }
        });
        nearShopTopBtn.setOnClickListener(v -> {
            this.limitDistance = "";
            getData(1, sort);
            nearShopTopRl.setVisibility(View.GONE);
        });
        nearShopSelNearLl.setOnClickListener(v -> chooseNear());
        nearShopSearch.setOnClickListener(v -> {
            Intent intent = new Intent(getContext(), SearchActivity.class);
            intent.putExtra("isSearchFrom", 2);
            startActivity(intent);
        });
        nearShopAddressLl.setOnClickListener(v -> RouterCommonUtils.startNoParameterActivity(NearShopActivity.this, RouterIntentConstant.MODULE_SHOPPING_SELECT_ADDRESS_LIST, CODE_COMMUNITY));
    }


    private void beginLocation() {
        LocationManager lm = new LocationManager();
        lm.getLocation(result -> {
            if (result.mResultId == 0) {
                lnToCommunity(result.mLocation.mLatitude, result.mLocation.mLongitude,"");
            } else {
                nearShopAdapter.setEmptyView(locationView);
                nearShopAddressLl.setVisibility(View.GONE);
            }
        }, this);
    }


    private void lnToCommunity(final double lat, final double lon,String cityCode) {
        new PoiManager(this, lat, lon, "", true, list -> {
            if (!Preconditions.isNullOrEmpty(list)) {
                NearShopActivity.this.mLon = list.get(0).getLatLonPoint().getLongitude() + "";
                NearShopActivity.this.mLat = list.get(0).getLatLonPoint().getLatitude() + "";
                NearShopActivity.this.limitDistance = "3000";
                BaseCommLocateInfo locateInfo = new BaseCommLocateInfo();
                locateInfo.lon = list.get(0).getLatLonPoint().getLongitude() + "";
                locateInfo.lat = list.get(0).getLatLonPoint().getLatitude() + "";
                locateInfo.city = list.get(0).getCityName();
                locateInfo.citycode = list.get(0).getCityCode();
                BaseSpUtils.getInstance().setCurrentCommuity(NearShopActivity.this, locateInfo);
                getData(1, sort);
                nearShopAddressLl.setVisibility(View.VISIBLE);
                nearShopAddress.setText(list.get(0).getTitle());
            } else {
                nearShopAdapter.setEmptyView(locationView);
                nearShopAddressLl.setVisibility(View.GONE);
            }
        },cityCode);

    }

    private void getData(int type, int sort) {
        if (type == 1) {
            page = 0;
            mPresenter.showShopDownStairs(page, size, mLon, mLat, "", mainBusinessId, limitDistance, sort, AppConstants.ONREFRESH);
        } else {
            page++;
            mPresenter.showShopDownStairs(page, size, mLon, mLat, "", mainBusinessId, limitDistance, sort, AppConstants.ONLOADMORE);
        }
    }


    @Override
    public void shopCategorys(CategoriesBean categoriesBean) {
        shopCategorysPop = new ShopCategorysPop(this, categoriesBean.get_embedded().getContent(), nearShopSelAllIv);
        shopCategorysPop.showOnAnchor(nearShopSelLl, RelativePopupWindow.VerticalPosition.BELOW, RelativePopupWindow.HorizontalPosition.ALIGN_LEFT, 0, 0);
        shopCategorysPop.setPopTypeChoose(this);
    }


    @Override
    public void shopDownStairsData(ShopDownStairsBean shopDownStairsBean, int type) {
        nearShopRefresh.finishRefresh();
        if (shopDownStairsBean.get_embedded() != null && shopDownStairsBean.get_embedded().getShopDownStairsViews() != null && shopDownStairsBean.get_embedded().getShopDownStairsViews().size() > 0) {
            if (type == AppConstants.ONREFRESH) {
                for (int i = 0; i < shopDownStairsBean.get_embedded().getShopDownStairsViews().size(); i++) {
                    List<ShopDownStairsBean.EmbeddedBeanX.ContentBean.EmbeddedBean.GoodsInfoViewListBean> listBean = shopDownStairsBean.get_embedded().getShopDownStairsViews().get(i).get_embedded().getGoodsInfoViewList();
                    if (listBean != null && listBean.size() > 0) {
                        listBean.add(listBean.size(), new ShopDownStairsBean.EmbeddedBeanX.ContentBean.EmbeddedBean.GoodsInfoViewListBean());
                    }
                }
                nearShopAdapter.setNewData(shopDownStairsBean.get_embedded().getShopDownStairsViews());
            } else {
                for (int i = 0; i < shopDownStairsBean.get_embedded().getShopDownStairsViews().size(); i++) {
                    List<ShopDownStairsBean.EmbeddedBeanX.ContentBean.EmbeddedBean.GoodsInfoViewListBean> listBean = shopDownStairsBean.get_embedded().getShopDownStairsViews().get(i).get_embedded().getGoodsInfoViewList();
                    if (listBean != null && listBean.size() > 0) {
                        listBean.add(listBean.size(), new ShopDownStairsBean.EmbeddedBeanX.ContentBean.EmbeddedBean.GoodsInfoViewListBean());
                    }
                }
                nearShopAdapter.addData(shopDownStairsBean.get_embedded().getShopDownStairsViews());
                nearShopAdapter.loadMoreComplete();
            }
        } else {
            if (type == AppConstants.ONREFRESH) {
                nearShopAdapter.setNewData(new ArrayList<>());
                nearShopAdapter.setEmptyView(noDataView);
            } else {
                nearShopAdapter.loadMoreEnd();
            }
        }
    }

    @Override
    public void showErro(String s, int type) {
        if (type == AppConstants.ONREFRESH) {
            nearShopRefresh.finishRefresh();
            nearShopAdapter.setEmptyView(errorView);
        } else {
            nearShopAdapter.loadMoreEnd();
        }
    }

    @Override
    public void popChoose(CategoriesBean.EmbeddedBeanXX.ContentBean entity) {
        nearShopSelAllTv.setText(entity.getName());
        this.mainBusinessId = entity.getId() + "";
        getData(1, sort);
    }


    //全部分类
    private void chooseAll() {
        nearShopSelAllTv.setTextColor(getResources().getColor(R.color.home_red));
        nearShopSelNearLl.setEnabled(true);
        nearShopSelNearTv.setTextColor(getResources().getColor(R.color.font_gary));
    }

    //离我最近
    private void chooseNear() {
        this.limitDistance = "3000";
        nearShopSelNearLl.setEnabled(false);
        nearShopSelNearTv.setTextColor(getResources().getColor(R.color.home_red));
        nearShopSelAllTv.setTextColor(getResources().getColor(R.color.font_gary));
        if (shopCategorysPop != null && shopCategorysPop.isShowing()) {
            shopCategorysPop.dismiss();
        }
        sort = 1;
        getData(1, sort);
    }


    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        getData(1, sort);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (CODE_COMMUNITY == requestCode && resultCode == RESULT_OK) {
            BaseCommLocateInfo baseCommLocateInfo = BaseSpUtils.getInstance().getCurrentCommuity(this);
            this.mLon = baseCommLocateInfo.lon;
            this.mLat = baseCommLocateInfo.lat;
            nearShopAddress.setText(baseCommLocateInfo.name);
            getData(1, sort);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        getData(2, sort);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
